package com.ctos.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctos.common.Result;
import com.ctos.entity.AddressBook;
import com.ctos.mapper.AddressBookMapper;
import com.ctos.service.AddressBookService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook>implements AddressBookService {
    @Override
    public void setDefault(Long id, Long userid) {
        //查询是否已有过默认地址
        LambdaQueryWrapper<AddressBook> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(id!=null, AddressBook::getUserId,userid);
        List<AddressBook> list = this.list(queryWrapper);
        for (AddressBook addressBook : list) {
            if (addressBook.getIsDefault()!=0){
                addressBook.setIsDefault(0);
                updateById(addressBook);
                break;
            }
        }


        LambdaQueryWrapper<AddressBook> qw =new LambdaQueryWrapper<>();
        qw.eq(id!=null,AddressBook::getId, id);
        AddressBook user = this.getOne(qw);
        user.setIsDefault(1);

        this.updateById(user);

    }
}
